package com.zamxie.core.utils;

import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.zamxie.oss.core.OssTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Description TODO
 * @Author zamxie
 * @Date 2024/3/25 下午1:50
 * @Version 1.0
 **/
@Slf4j
@Component
public class OssUtil {

    private static String endpoint;
    private static String accessKey;
    private static String secretKey;
    private static String bucketName;
    private static OssTemplate ossTemplate;

    @Value("${oss.endpoint}")
    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }
    @Value("${oss.accessKey}")
    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }
    @Value("${oss.secretKey}")
    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }
    @Value("${oss.bucketName}")
    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    @Autowired
    public OssUtil(OssTemplate ossTemplate) {
        this.ossTemplate=ossTemplate;
    }

    /**
     * 文件上传
     * @param file 文件
     * @param objectName 文件路径（xxx/xxxx/xxx）/文件名称
     * @return
     */
    public static boolean upload(MultipartFile file,String objectName){
        try {
            PutObjectResult putObjectResult = ossTemplate.putObject(bucketName, objectName, file.getInputStream(), file.getContentType());
            if(putObjectResult!=null){
                return true;
            }
        } catch (Exception e) {
            log.error("文件上传oss服务异常:{}",e);
        }finally {
            ossTemplate.shutdown();
        }
        return false;
    }

    /**
     * 文件上传
     * @param file 文件流
     * @param objectName 文件路径（xxx/xxxx/xxx）/文件名称
     * @param contentType 原文件类型（application/msword、application/vnd.ms-excel等）
     * @return
     */
    public static boolean upload(InputStream file, String objectName,String contentType){
        try {
            PutObjectResult putObjectResult = ossTemplate.putObject(bucketName, objectName, file, contentType);
            if(putObjectResult!=null){
                return true;
            }
        } catch (Exception e) {
            log.error("oss文件上传服务异常:{}",e);
        }finally {
            ossTemplate.shutdown();
        }
        return false;
    }

    /**
     *文件上传
     * @param file 文件流
     * @param objectName 文件路径（xxx/xxxx/xxx）/文件名称
     * @return
     */
    public static boolean upload(InputStream file, String objectName){
        try {
            PutObjectResult putObjectResult = ossTemplate.putObject(bucketName, objectName, file);
            if(putObjectResult!=null){
                return true;
            }
        } catch (Exception e) {
            log.error("oss文件上传服务异常:{}",e);
        }finally {
            ossTemplate.shutdown();
        }
        return false;
    }

    /**
     *文件上传
     * @param sourcefilepath 源文件路径
     * @param objectName 文件路径（xxx/xxxx/xxx）/文件名称
     * @return
     */
    public static boolean upload(String sourcefilepath, String objectName) {
        try (InputStream file = new FileInputStream(sourcefilepath)) {
            PutObjectResult putObjectResult = ossTemplate.putObject(bucketName, objectName, file);
            return putObjectResult != null;
        } catch (FileNotFoundException e) {
            log.error("oss文件上传:文件未找到: {}", sourcefilepath);
        } catch (Exception e) {
            log.error("oss文件上传异常: {}", e.getMessage());
        }
        return false;
    }

    /**
     * 文件下载（使用完此方法需要关闭InputStream，释放资源）
     * @param objectName 文件路径（xxx/xxxx/xxx）/文件名称
     * @return
     */
    public static InputStream download(String objectName){
        try {
            S3Object object = ossTemplate.getObject(bucketName, objectName);
            if(object!=null){
                InputStream file = object.getObjectContent();
                return file;
            }
        } catch (Exception e) {
            log.error("oss文件下载服务异常:{}",e);
        }
        return null;
    }

    /**
     * 文件下载
     * @param objectName 文件路径（xxx/xxxx/xxx）/文件名称
     * @return
     */
    public static byte[] downloadToBytes(String objectName){
        ByteArrayOutputStream bos=null;
        try {
            InputStream inputStream = download(objectName);
            if(inputStream!=null) {
                byte[] buffer = new byte[1024 * 1024];
                bos = new ByteArrayOutputStream();
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                return bos.toByteArray();
            }
        } catch (Exception e) {
            log.error("oss文件下载异常:{}",e);
        }finally {
            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error("oss文件下载流关闭异常:{}",e);
                }
            }
        }
        return null;
    }

    /**
     * 文件删除
     * @param objectName
     * @return
     */
    public static boolean removeFile(String objectName){
        try {
            boolean exist = ossTemplate.doesObjectExist(bucketName, objectName);
            if(exist) {
                ossTemplate.removeObject(bucketName, objectName);
                return true;
            }else{
                log.error("文件不存在:{}",objectName);
            }
        } catch (Exception e) {
            log.error("oss文件删除服务异常:{}",e);
        }finally {
            ossTemplate.shutdown();
        }
        return false;
    }

}
